<template>
    <div class="wrapper">
        <t-card>
            <t-row class="table-header">
                <t-space>
                    <t-input v-model="searchKey" placeholder="请输入搜索的角色名" size="medium"></t-input>
                    <t-button theme="primary" size="medium" @click="handleSearch">搜索</t-button>
                    <t-button theme="primary" size="medium" @click="showAddDialog">添加</t-button>
                </t-space>
            </t-row>
            <t-table :row-key="rowKey" :data="roleListData" :columns="columns" :size="size" :bordered="bordered"
                :stripe="stripe" :resizable="resizable" :loading="loading" :pagination="pagination"
                @page-change="rehandlePageChange" class="table-content">
                <template #options="{ row }">
                    <t-space>
                        <t-button theme="default" size="small" @click="showEditDialog(row)">编辑</t-button>
                        <t-button theme="default" size="small" @click="showPermissionDialog(row)">权限</t-button>
                        <t-button theme="danger" size="small" @click="handleDelete(row)">删除</t-button>
                    </t-space>
                </template>
            </t-table>
        </t-card>
        <t-dialog :visible="visibleAdd" header="添加角色" :footer="false" width="400px" @close="visibleAddClose">
            <t-form ref="addFormRef" :data="addForm" :rules="addRules" :label-width="80" class="add-form"
                @submit="handleAddConfirm">
                <t-form-item label="角色名" name="name">
                    <t-input v-model="addForm.name" placeholder="请输入角色名" size="medium"></t-input>
                </t-form-item>
                <t-form-item label="角色标识" name="code">
                    <t-input v-model="addForm.code" placeholder="请输入角色标识" size="medium"></t-input>
                </t-form-item>
                <t-form-item label="角色描述" name="description">
                    <t-input v-model="addForm.description" placeholder="请输入角色描述" size="medium"></t-input>
                </t-form-item>
                <t-form-item>
                    <t-button type="submit" theme="primary" block>确定</t-button>
                </t-form-item>
            </t-form>
        </t-dialog>
        <t-dialog :visible="visibleEdit" header="编辑角色" :footer="false" width="500px" @close="visibleEditClose">
            <t-form ref="editFormRef" :data="editForm" :rules="editRules" :label-width="80" class="add-form"
                @submit="handleEditConfirm">
                <t-form-item label="角色名" name="name">
                    <t-input v-model="editForm.name" placeholder="请输入角色名" size="medium"></t-input>
                </t-form-item>
                <t-form-item label="角色标识" name="code">
                    <t-input v-model="editForm.code" placeholder="请输入角色标识" size="medium"></t-input>
                </t-form-item>
                <t-form-item label="角色描述" name="description">
                    <t-input v-model="editForm.description" placeholder="请输入角色描述" size="medium"></t-input>
                </t-form-item>
                <t-form-item>
                    <t-button type="submit" theme="primary" block>确定</t-button>
                </t-form-item>
            </t-form>
        </t-dialog>
        <t-dialog :visible="visiblePermission" header="角色权限" :footer="false" @close="visiblePermissionClose">
            <div style="max-height: 50vh; overflow-y: auto;">
                <t-space direction="vertical">
                    <t-tree ref="permissionTree" :data="permissionData" :checkable="true" :hover="true"
                        :value="checkedPermissions" @change="onPermissionChange" value-mode="all"
                        hover-theme="highlight" transition :keys="{
                            value: 'id',
                            label: 'label',
                            children: 'children'
                        }" />
                </t-space>
            </div>
            <t-button theme="primary" block @click="handlePermissionConfirm">确定</t-button>
        </t-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next';
import type { RoleList, addRoleForm, editRoleForm, SubmitParams, PermissionNode } from '@/types/interface';
import { getRoleList, addRole, editRole, deleteRole, getRolePermission, updateRolePermission } from '@/api/role';
import { FormInstanceFunctions } from 'tdesign-vue-next';

import { useUserStore } from '@/store';
const userStore = useUserStore();

// 搜索框
const searchKey = ref('');

// 表格属性
const rowKey = ref('id');
const roleListData = ref<RoleList[]>([]);
const size = ref('medium');
const bordered = ref(true);
const stripe = ref(true);
const resizable = ref(true);
const loading = ref(false);
const pagination = ref({
    defaultCurrent: 1,
    defaultPageSize: 10,
    total: 0,
    current: 1,
    pageSize: 10,
    pageSizeOptions: [2, 5, 10],
});

const uid = userStore.id;

// 处理分页变化
const rehandlePageChange = async (curr: any, pageInfo: unknown) => {
    pagination.value.current = curr.current;
    pagination.value.pageSize = curr.pageSize;
    await getRoleListData();
};

// 表格列配置
const columns = ref([
    {
        title: '角色名',
        colKey: 'name',
        align: 'center',
        width: 80,
    },
    {
        title: '角色标识',
        colKey: 'code',
        align: 'center',
        width: 80,
    },
    {
        title: '角色描述',
        colKey: 'description',
        align: 'center',
        width: 120,
    },
    {
        title: '创建时间',
        colKey: 'create_time',
        align: 'center',
        width: 140,
    },
    {
        title: '操作',
        colKey: 'options',
        align: 'center',
        width: 140,
    },
]);

// 添加弹窗
const visibleAdd = ref(false);
const addFormRef = ref<FormInstanceFunctions>();
const addForm = ref<addRoleForm>({
    name: '',
    code: '',
    description: ''
});
const addRules = ref({
    name: [
        { required: true, message: '请输入角色名', type: 'error' }
    ],
    code: [
        { required: true, message: '请输入角色标识', type: 'error' }
    ],
});
const showAddDialog = () => {
    addFormRef.value?.reset()
    addForm.value.name = "";
    addForm.value.code = "";
    addForm.value.description = "";
    visibleAdd.value = true;
};
const handleAddConfirm = async ({ validateResult, firstError }: SubmitParams) => {
    if (!validateResult) {
        console.error(firstError);
        return;
    }
    try {
        loading.value = true;
        const params = {
            uid: uid,
            name: addForm.value.name,
            code: addForm.value.code,
            description: addForm.value.description,
        }
        const res = await addRole(params);
        if (res.errcode == 0) {
            MessagePlugin.success(res.message, 1000).then(() => {
                visibleAdd.value = false;
                getRoleListData();
            })
        }
    } catch (error) {
        console.error('请求失败', error);
    } finally {
        loading.value = false;
    }
};
const visibleAddClose = () => {
    visibleAdd.value = false;
};

// 编辑弹窗
const visibleEdit = ref(false);
const editFormRef = ref<editRoleForm>({
    id: 0,
    name: '',
    code: '',
    description: '',
});
const editForm = ref<editRoleForm>({
    id: 0,
    name: '',
    code: '',
    description: '',
});
const editRules = ref({
    name: [
        { required: true, message: '请输入角色名', type: 'error' }
    ],
    code: [
        { required: true, message: '请输入角色标识', type: 'error' }
    ],
});
const showEditDialog = (row: any) => {
    visibleEdit.value = true;
    editForm.value.id = row.id;
    editForm.value.name = row.name;
    editForm.value.code = row.code;
    editForm.value.description = row.description;
};
const handleEditConfirm = async ({ validateResult, firstError }: SubmitParams) => {
    if (!validateResult) {
        console.error(firstError);
        return;
    }
    try {
        loading.value = true;
        const params = {
            id: editForm.value.id,
            name: editForm.value.name,
            code: editForm.value.code,
            description: editForm.value.description,
            uid: uid,
        }
        const res = await editRole(params);
        if (res.errcode == 0) {
            MessagePlugin.success(res.message, 1000).then(() => {
                visibleEdit.value = false;
                getRoleListData();
            })
        }
    } catch (error) {
        console.error('请求失败', error);
    } finally {
        loading.value = false;
    }
};
const visibleEditClose = () => {
    visibleEdit.value = false;
};

// 权限弹窗
const visiblePermission = ref(false);
const permissionData = ref<PermissionNode[]>([]);
const checkedPermissions = ref<(string | number)[]>([]);
const currentRoleId = ref(0);

const showPermissionDialog = async (row: RoleList) => {
    visiblePermission.value = true;
    loading.value = true;
    currentRoleId.value = row.id;
    try {
        const params = {
            id: currentRoleId.value,
        }
        const res = await getRolePermission(params);
        if (res.errcode == 0) {
            permissionData.value = res.data.permissionTree;
            checkedPermissions.value = res.data.checkedKeys;
            console.log(permissionData.value);
            console.log(checkedPermissions.value);
        }
    } catch (error) {
        MessagePlugin.error('获取权限列表失败');
    } finally {
        loading.value = false;
    }
};

const onPermissionChange = (value: Array<string | number>) => {
    checkedPermissions.value = value.filter(id =>
        typeof id === 'number' || !id.toString().startsWith('module_')
    );
};


const handlePermissionConfirm = async () => {
    loading.value = true;
    try {
        const params = {
            role_id: currentRoleId.value,
            permissionIds: checkedPermissions.value,
            uid: uid
        };
        const res = await updateRolePermission(params);
        if (res.errcode == 0) {
            MessagePlugin.success(res.message, 1000).then(() => {
                visiblePermission.value = false;
            });
        }
    } catch (error) {
        console.error('更新权限失败', error);
        // MessagePlugin.error('更新权限失败');
    } finally {
        loading.value = false;
    }
};

const visiblePermissionClose = () => {
    visiblePermission.value = false;
    permissionData.value = [];
    checkedPermissions.value = [];
    currentRoleId.value = 0;
};


const handleDelete = async (row: any) => {
    const params = {
        id: row.id,
        uid: uid,
    }
    loading.value = true;
    const dialog = DialogPlugin.confirm({
        header: '删除角色',
        body: '是否删除该角色，此操作是不可逆的？',
        confirmBtn: '确定',
        cancelBtn: '取消',
        onConfirm: async () => {

            const res = await deleteRole(params);
            if (res.errcode == 0) {
                MessagePlugin.success(res.message, 1000).then(() => {
                    dialog.destroy();
                    pagination.value.current = 1;
                    getRoleListData();
                })
            }

        }
    });
    loading.value = false;
}


// 搜索
const handleSearch = () => {
    pagination.value.current = 1;
    getRoleListData();
};

// 获取用户列表
const getRoleListData = async () => {
    const params = {
        page: pagination.value.current,
        pageSize: pagination.value.pageSize,
        searchKey: searchKey.value,
        uid: uid,
    };
    try {
        loading.value = true;
        const res = await getRoleList(params);
        roleListData.value = res.data.roles;
        pagination.value.total = res.data.total;
        loading.value = false;
    } catch (error) {
        console.error('获取角色列表失败', error);
        // MessagePlugin.error('获取角色列表失败');
    } finally {
        loading.value = false;
    }
};

onMounted(() => {
    getRoleListData();
});
</script>

<style scoped>
.wrapper {
    padding: 20px;
}

.table-header {
    margin-top: 20px;
    margin-bottom: 20px;
}

.table-content {
    min-width: 760px;
}

.add-form {
    margin-top: 10px;
}
</style>
